package com.javastar.modules.security.handler;

import com.javastar.common.exception.ErrorCode;
import com.javastar.common.result.Result;
import com.javastar.common.utils.ResponseUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证异常处理器
 *
 * @author zxx
 * @date 2023/7/25
 */
@Component
public class SysAuthenticationFailureHandler implements AuthenticationFailureHandler {
    /**
     * 登陆认证失败，响应错误信息
     * @param request the request during which the authentication attempt occurred.
     * @param response the response.
     * @param exception the exception which was thrown to reject the authentication
     * request.
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        ResponseUtil.write(response, new Result().error(ErrorCode.USERNAME_OR_PASSWORD_ERROR));
    }
}
